﻿// ------------------------------------------------------------------------
// 项目名称：Canroc.Net 
// 版权归属：Canroc（https://gitee.com/canroc）
//
// 许可证信息
// Canroc.Net项目主要遵循 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-APACHE 文件。
//
// 使用条款：
// 1.使用本项目应遵守相关法律法规和许可证的要求。
// 2.不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动。
// 3.任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任
//
// 免责声明
// 对于因使用本代码而产生的任何直接、间接、偶然、特殊或后果性损害，我们不承担任何责任。
//
// 其他重要信息
// Canroc.Net 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。
// ------------------------------------------------------------------------

using Canroc.Net.Core.Extension;
using Canroc.Net.Core.Model;
using System.Linq.Expressions;
using System.Reflection;

namespace Canroc.Net.Repository;

/// <summary>
///     SqlSugar 扩展
/// </summary>
public static class SqlSugarExtension
{
    /// <summary>
    ///     组装联级选择器结构
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="list">原始数据集</param>
    /// <param name="idProperty">主键</param>
    /// <param name="parentIdProperty">父级Id</param>
    /// <param name="labelProperty">选项的文本</param>
    /// <param name="rootValue">顶级值</param>
    /// <param name="orderProperty">排序项</param>
    /// <returns></returns>
    private static List<CascaderOptionOutputModel> AssembleOrgOption<T>(List<T> list, PropertyInfo idProperty,
        PropertyInfo parentIdProperty, PropertyInfo labelProperty, object? rootValue,
        PropertyInfo? orderProperty = null)
    {
        List<CascaderOptionOutputModel> result = [];
        if (rootValue is null)
        {
            return result;
        }

        var newList = list.Where(l => parentIdProperty.GetValue(l)!.Equals(rootValue));

        IEnumerable<T> enumerable = newList as T[] ?? newList.ToArray();
        if (orderProperty is not null)
        {
            _ = enumerable.OrderBy(_ => orderProperty);
        }

        result.AddRange(enumerable.Select(item => new CascaderOptionOutputModel
        {
            Label = labelProperty.GetValue(item)!.ParseToString(),
            Value = idProperty.GetValue(item),
            Children = AssembleOrgOption(list, idProperty, parentIdProperty, labelProperty,
                idProperty.GetValue(item), orderProperty)
        }));

        return result;
    }

    /// <param name="query">SqlSugar查询器</param>
    /// <typeparam name="T">实体类型</typeparam>
    extension<T>(ISugarQueryable<T> query)
    {
        /// <summary>
        ///     查询条数扩展
        /// </summary>
        /// <param name="isTake">是否限制条数</param>
        /// <param name="num">返回条数</param>
        /// <returns></returns>
        public ISugarQueryable<T> TakeIf(bool isTake, int num)
        {
            return isTake ? query.Take(num) : query;
        }

        /// <summary>
        ///     分页查询扩展
        /// </summary>
        /// <param name="pageIndex">分页索引</param>
        /// <param name="pageSize">分页大小</param>
        /// <returns></returns>
        public async Task<PageModel<T>> ToPageAsync(int pageIndex,
            int pageSize)
        {
            RefAsync<int> totalCount = 0;
            var items = await query.ToOffsetPageAsync(pageIndex, pageSize, totalCount);
            var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
            return new PageModel<T>
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                Items = items,
                TotalCount = (int)totalCount,
                TotalPages = totalPages,
                HasNextPages = pageIndex < totalPages,
                HasPrevPages = pageIndex - 1 > 0
            };
        }

        /// <summary>
        ///     联集选择器扩展
        /// </summary>
        /// <param name="primaryKeyExpression">主键</param>
        /// <param name="parentIdExpression">父级Id</param>
        /// <param name="labelNameExpression">选项的文本</param>
        /// <param name="rootValue">顶级值</param>
        /// <param name="orderExpression">排序项</param>
        /// <returns></returns>
        public async Task<List<CascaderOptionOutputModel>> ToCascaderOptionTreeAsync(
            Expression<Func<T, object>> primaryKeyExpression,
            Expression<Func<T, object>> parentIdExpression,
            Expression<Func<T, object>> labelNameExpression,
            object rootValue,
            Expression<Func<T, object>>? orderExpression = null)
        {
            var list = await query.ToListAsync();

            var entityInfo = typeof(T);
            var idName = ExpressionTool.GetMemberName(primaryKeyExpression);
            var idProperty = entityInfo.GetProperty(idName);
            var pIdName = ExpressionTool.GetMemberName(parentIdExpression);
            var parentIdProperty = entityInfo.GetProperty(pIdName);
            var labelName = ExpressionTool.GetMemberName(labelNameExpression);
            var labelProperty = entityInfo.GetProperty(labelName);
            var orderName = ExpressionTool.GetMemberName(orderExpression);
            var orderProperty = entityInfo.GetProperty(orderName);

            if (idProperty is null || parentIdProperty is null || labelProperty is null)
            {
                return [];
            }

            return AssembleOrgOption(list, idProperty, parentIdProperty, labelProperty, rootValue, orderProperty);
        }
    }
}